import {Component, OnInit,HostListener} from '@angular/core';
import {DatePipe} from '@angular/common';
import {EmitService} from '../../../providers/emit.service';
import {HttpService} from '../../../providers/http.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {debounceTime, distinctUntilChanged, first, map, switchMap} from 'rxjs/internal/operators';
import {Xutils} from '../../../utils/xutils';

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.css'],

})
export class RoleComponent implements OnInit {

  autoHeight: number = 480;

  tab = {
    name: '角色管理',
    url: '/page/system/role',
    closeIcon: true
  };

  loading = false;
  _page = {rows: [], total: 0};
  _cnd: any = {pageNum: 1, pageSize: 10};
  createTimes;

  constructor(public emitService: EmitService,
              private httpService: HttpService,
              private message: NzMessageService,
              private fb: FormBuilder,
              private datePipe: DatePipe) {
  }


  ngOnInit() {

    //初始化表单
    this.buildForm();

    // 通知父组件
    this.emitService.tabsEmit.emit(this.tab);

    // 列表查询
    this.search(true);


  }


  search(reset: boolean = false): void {
    if (reset) {
      let currentPageNum=this._cnd.pageNum;
      let currentPageSize = this._cnd.pageSize;
      this.createTimes=null;
      this._cnd={pageNum: 1, pageSize: currentPageSize};
    }

    this._cnd.params = {};
    this.checkedIdMap = {};
    if (this.createTimes != null && this.createTimes.length>0) {
      this._cnd.params = {
        beginCreateTime:this.datePipe.transform(this.createTimes[0],'yyyy-MM-dd')+' 00:00:00',
        endCreateTime:this.datePipe.transform(this.createTimes[1],'yyyy-MM-dd')+' 23:59:59',
      }
    }


    this.loading = true;
    this.httpService.post('system/role/list', this._cnd,  (result)=> {
      this.loading = false;
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this._page = result.data;
    },(errorResult)=>{
      this.loading = false;
      this.message.error(errorResult.msg);
    });
  }

  // checkbox
  isAllChecked = false;
  checkedIdMap: { [key: string]: boolean } = {};
  isEditBtn = false;
  isDeleteBtn = false;

  checkedAll(isChecked: boolean) {
    this._page.rows.forEach(item => (this.checkedIdMap[item.roleId] = isChecked));
    this.checkedChange();
  }

  checkedChange() {
    this.isAllChecked = this._page.rows.every(item => this.checkedIdMap[item.roleId]);
    this.isDeleteBtn = this._page.rows.some(item => this.checkedIdMap[item.roleId]);
    this.isEditBtn = false;
    let rows = this._page.rows;
    let count = 0;
    for (let i = 0; i < rows.length; i++) {
      if (this.checkedIdMap[rows[i].roleId]) {
        count++;
      }
    }
    if (count == 1) {
      this.isEditBtn = true;
    }
  }

  // form crud
  modalWidth=800;
  modalTitle='角色信息';
  validateForm: FormGroup;
  isVisible = false;
  isOkLoading = false;

  buildForm(){
    this.validateForm = this.fb.group({
      roleId:[null,null],
      roleName: [null ,[Validators.required], this.asyncUniqueValidate('roleName')],
      roleKey: [null ,[Validators.required], this.asyncUniqueValidate('roleKey')],
      roleSort: [null ,[Validators.required]],
      status: [null ,[Validators.required]],
      remark: [null ,null],

    });
  }

  saveOrUpdate(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return;
    }
    this.isOkLoading = true;
    let url = 'system/role/add';
    let roleId = this.validateForm.value.roleId;
    if (roleId && roleId > 0) {
      url = 'system/role/edit';
    }
    this.httpService.post(url, this.validateForm.value,  (result)=> {
      this.isOkLoading = false;
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.isVisible = false;
      this.message.success('操作成功');
      this.search();
    },(errorResult)=>{
      this.isOkLoading = false;
      this.isVisible = false;
      this.message.error(errorResult.msg);
    });
  }

  deleteOne(id){
    this.httpService.post('system/role/delete', {ids:id},  (result)=> {
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.message.success('删除成功');
      this.search();
    },(errorResult)=>{
      this.message.error(errorResult.msg);
    });
  }

  deleteSome(){
    let ids =  this.getCheckedIds();
    this.deleteOne(ids);
  }

  editInfo(id){
    this.httpService.post('system/role/getById', {roleId:id},  (result)=> {
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.openOrCloseModal(true);
      this.validateForm.patchValue(result.data);
    },(errorResult)=>{
      this.message.error(errorResult.msg);
    });
  }

  // 列表上面的编辑按钮
  editInfoTop(){
    let id = this.getCheckedIds();
    this.editInfo(id);
  }

  cancelConfirm(){
  }

  openOrCloseModal(isVisible): void {
    this.autoHeight = document.documentElement.clientHeight -250;
    this.isVisible = isVisible;
    this.isOkLoading = false;
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  getCheckedIds(){
    let ids = [];
    for (const key in this.checkedIdMap) {
      if(this.checkedIdMap[key]){
        ids.push(key);
      }
    }
    return ids.join(",");
  }

  //异步验证
  asyncUniqueValidate(key) {
    return (control: FormControl): any => {
      return control.valueChanges.pipe(
        distinctUntilChanged(),
        debounceTime(400),
        switchMap(() => this.isExist(control,key)),
        map(res => res['code'] == 0 ? {duplicate: true} : null),
        first()
      );
    };
  }

  isExist(control,k) {
    let param = {};
    param[k] = control.value;
    let roleId = this.validateForm.value.roleId;
    if (roleId && roleId > 0) {
      param['roleId'] = roleId;
    }
    return this.httpService.p('system/role/isExist', param);
  }

  //分配用户
  isUserVisible = false;

  toUser(){
    this.isUserVisible = true;
  }

  //响应式
  resizeWidth;
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.resizeWidth = event.target.innerWidth;
    //console.log(this.resizeWidth);
  }

  isSm(){
    if(this.resizeWidth<=800 || Xutils.isMobile()){
      return true;
    }
    return false;
  }
}
